package com.xzg.completeMissionApply.service;

import com.xzg.common.constants.Constant;
import com.xzg.common.exception.XZGException;
import com.xzg.common.push.AppPush;
import com.xzg.common.vo.QueryCondition;
import com.xzg.completeMissionApply.dao.CompleteMissionApplyMapper;
import com.xzg.completeMissionApply.entity.CompleteMissionApply;
import com.xzg.integral.dao.IntegralMapper;
import com.xzg.integral.entity.Integral;
import com.xzg.middleTable.dao.IntegralUserMapper;
import com.xzg.middleTable.dao.UserCompleteMapper;
import com.xzg.middleTable.entity.IntegralUser;
import com.xzg.mission.dao.MissionMapper;
import com.xzg.mission.entity.Mission;
import com.xzg.myMission.dao.MyMissionMapper;
import com.xzg.myMission.entity.MyMission;
import com.xzg.past.dao.PastRecordsMapper;
import com.xzg.past.entity.PastRecords;
import com.xzg.user.dao.UserMapper;
import com.xzg.user.entity.User;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class CompleteMissionServiceImpl implements CompleteMissionService {

    @Autowired
    private CompleteMissionApplyMapper completeMissionApplyMapper;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private UserCompleteMapper completeMapper;

    @Autowired
    private MissionMapper missionMapper;

    @Autowired
    private MyMissionMapper myMissionMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IntegralMapper integralMapper;

    @Autowired
    private PastRecordsMapper pastRecordsMapper;

    @Autowired
    private IntegralUserMapper integralUserMapper;

    /**
     *@Author Ye
     *Date 2018-03-25 16:25
     *@Description 需要任务的名称，任务的内容，备注信息，任务的发布人
     * 新加推送
     */
    @Override
    @Transactional
    public void start(QueryCondition condition) throws XZGException {
        //查询此人是否重复申请
        int count = completeMissionApplyMapper.findDistinct(condition.getMissionId());
        if (count > 0) {
            throw new XZGException("已有任务，请勿重复申请");
        }
        CompleteMissionApply completeMissionApply = new CompleteMissionApply();
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute("userinfo");
        Mission mission = missionMapper.selectByPrimaryKey(condition.getMissionId());
        completeMissionApply.setPublisher(condition.getPublisher());
        completeMissionApply.setApplyUsername(user.getUsername());
        completeMissionApply.setComments(condition.getComments());
        completeMissionApply.setMissionName(condition.getMissionName());
        completeMissionApply.setMissionId(condition.getMissionId());
        completeMissionApply.setAward(condition.getAward());
        completeMissionApply.setStatus(Constant.APPLY_STATUS_ONGOING);
        completeMissionApply.setUserId(user.getId());
        completeMissionApply.setStartDate(new Date());
        completeMissionApplyMapper.insertSelective(completeMissionApply);
        Map<String, Object> map = new HashMap<>();
        map.put(Constant.COMPLETE_APPLY_SIGN, completeMissionApply);
        String username = mission.getPublisher();
        username = username +"1complete";
        map.put(Constant.NEXT_HANDLER, username);
        ProcessInstance instance = runtimeService.startProcessInstanceByKey(Constant.COMPLETE_APPLY_FLOW_ID, map);
        Task task = taskService.createTaskQuery().processInstanceId(instance.getId()).singleResult();
        taskService.complete(task.getId(),map);
        AppPush.pushSingle("{\"title\":\"猫咪老师\",\"content\":\"喵！~任务完成已申请！\"}", user.getCID());
        AppPush.pushSingle2("{\"title\":\"猫咪老师\",\"content\":\"喵！~任务完成已申请！\",\"payload\":\"喵！~\"}", user.getCID());
    }

    @Override
    @Transactional
    public void listTask(String username) {
        List<CompleteMissionApply> list = new ArrayList<>();
        username = username + "1";
        List<Task> tasks = taskService.createTaskQuery().processVariableValueEquals(username).list();
        if(CollectionUtils.isNotEmpty(tasks)) {
            for (Task task: tasks) {
                Map<String,Object> variable = taskService.getVariables(task.getId());
                CompleteMissionApply complete = (CompleteMissionApply) variable.get(Constant.COMPLETE_APPLY_SIGN);
                complete.setTaskId(task.getId());
                list.add(complete);
            }
        }
    }

    @Override
    @Transactional
    public int approve(QueryCondition condition) throws XZGException {
        int i = 0;
        Mission mission = new Mission();
        mission.setMissionId(condition.getMissionId());
        MyMission myMission = new MyMission();
        myMission.setUserId(condition.getUserId());
        taskService.createTaskQuery().taskId(condition.getTaskId()).singleResult();

//        if()
        if(Constant.MISSION_STATUS_COMPLETE .equals(condition.getStatus())) {
            mission.setTaskStatus(Constant.MISSION_STATUS_COMPLETE);
            missionMapper.updateByPrimaryKeySelective(mission);
            //修改申请人的任务表状态
            myMission.setTaskStatus(Constant.MISSION_STATUS_COMPLETE);
            myMissionMapper.updateByPrimaryKeySelective(myMission);
            //查询该任务奖励多少积分
            mission = missionMapper.selectByPrimaryKey(condition.getMissionId());
            //查出当前用户还有多少积分额度
            User user = (User) SecurityUtils.getSubject().getSession().getAttribute("userinfo");
            IntegralUser integralUser =integralUserMapper.selectByUserId(user.getId());
            if(integralUser.getIntegralcount()-mission.getAward()<0) {
                throw new XZGException("积分不足");
            }
            //扣掉审批人的积分额度
            integralUser.setUsId(user.getId());
            integralUser.setIntegralcount(integralUser.getIntegralcount()-mission.getAward());
            integralUserMapper.updateByPrimaryKeySelective(integralUser);
            //加积分
            Integral integral = integralMapper.selectByUserId(condition.getUserId());
            integral.setCountIntegral(integral.getCountIntegral()+mission.getAward());
            integralMapper.updateByPrimaryKeySelective(integral);
            //给申请人发推送
            user = userMapper.selectByPrimaryKey(condition.getUserId());
            AppPush.pushSingle("{\"title\":\"猫咪老师\",\"content\":\"喵！~任务已完成！\"}", user.getCID());
            AppPush.pushSingle2("{\"title\":\"猫咪老师\",\"content\":\"喵！~任务已完成！\",\"payload\":\"喵！~\"}", user.getCID());
            i = Constant.APPLY_STATUS_PSSS;
        } else if(Constant.APPLY_STATUS_REFUSE.equals(condition.getStatus())) {
           mission.setTaskStatus(Constant.APPLY_STATUS_REFUSE);
           missionMapper.updateByPrimaryKeySelective(mission);
           User user = userMapper.selectByPrimaryKey(condition.getUserId());
            AppPush.pushSingle("{\"title\":\"猫咪老师\",\"content\":\"喵！~任务完成被拒绝！\"}", user.getCID());
            AppPush.pushSingle2("{\"title\":\"猫咪老师\",\"content\":\"喵！~任务完成被拒绝！\",\"payload\":\"喵！~\"}", user.getCID());
            i = Constant.APPLY_STATUS_REFUSE;
        }
        //删除完成任务申请
        completeMissionApplyMapper.deleteByPrimaryKey(condition.getCompleteId());
        //删除用户中我的任务中的任务并把他加到历史任务表中,已经查到了任务的详细信息把他赋值到历史任务表
        PastRecords pastRecords = new PastRecords();
        pastRecords.setComments(mission.getContent());
        pastRecords.setMissionId(mission.getMissionId());
        pastRecords.setPublisher(mission.getPublisher());
        pastRecords.setStartDate(mission.getStartDate());
        pastRecords.setStatus(mission.getTaskStatus());
        pastRecords.setMissionName(mission.getMissionName());
        pastRecordsMapper.insertSelective(pastRecords);
        myMissionMapper.deleteByPrimaryKey(mission.getMissionId());
        taskService.complete(condition.getTaskId());
        return i;
    }
}
